如何區分數字字符串和字符串? (How do i distinguish between number string and character string?)


問題描述

如何區分數字字符串和字符串? (How do i distinguish between number string and character string?)

var snumber1 = "123456789";
var scharacter2 = "abcdefgh";

there're two strings. how do i make sure snumber1 contains only numbers?? What regex??

‑‑‑‑‑

參考解法

方法 1:

The regex to determine if something is just numbers is this:

"^\d+$"  or  "^[0‑9]+$"

Source: StackOverFlow 273141

方法 2:

var snumber1 = "123456789";
//built‑in function
alert ( !isNaN ( snumber1 ) );
//regexp
alert ( /^[0‑9]+$/.test ( snumber1 ) );
//another regexp
alert ( /^\d+$/.test ( snumber1 ) );
//convert to Number object
alert ( parseFloat ( snumber1 ) === Number ( snumber1 ) );

方法 3:

You need this function:

isNaN(string)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN

方法 4:

Regular expressions are unnecessary:

var snumber1 = "123456789",
    scharacter2 = "abcdefgh";

if ( isNaN(+snumber1) ) {
  alert('snumber is not a number!');
}

if ( !isNaN(+scharacter2) ) {
  alert('scharacter2 is not a string!');
}

Note that I am using the + operator to do type coercion. Doing so will always result in a number or NaN. If you use the parseInt or parseFloat functions you could get '10' from parseInt('010abc', 10). This clearly doesn't pass your test for "only numbers" (*).

方法 5:

You should use SWITCH statements instead of IF.

var valueA=100

switch(/^[0‑9]+$/.test( valueA ))
{
    case false:
        alert ("'" + valueA + "'" + " Is NOT a number.Try Again");
        break;
    case true;
        alert ("you've got numbers")
        break;
}

This will return true.

(by DrStrangeLoveJakeJBakudanJoeJames SumnersCodeyKane)

參考文件

  1. How do i distinguish between number string and character string? (CC BY‑SA 3.0/4.0)

#string #javascript #RegEx






相關問題

VB.net 如何讓流閱讀器忽略某些行? (VB.net how to make stream reader ignore some line?)

Perl Text::CSV_XS 從字符串中讀取 (Perl Text::CSV_XS read from string)

在 D3 中用逗號格式化數字 (Formatting numbers with commas in D3)

我應該使用什麼-String 或 StringBuilder 將 SQL 查詢存儲在使用許多不同 SQL 查詢的代碼中 (what should i use-String or StringBuilder for storing SQL queries in a code which uses many different SQL queries)

在 python 3.5 的輸入列表中添加美元符號、逗號和大括號 (Adding dollar signs, commas and curly brackets to input list in python 3.5)

使用正則表達式處理字符串 (String Manipulation with regular expression)

如何區分數字字符串和字符串? (How do i distinguish between number string and character string?)

如何將單詞的結尾與 Ruby 中的哈希進行比較? (How can I compare the ending of a word with a hash in Ruby?)

在 Python 列表中查找位於特定字符串之間的字符串 (Find Strings Located Between Specific Strings in List Python)

大寫替代字母 (Alternate letters in upper case)

查找 ia strn 列在同一數據框中的列表列中,並創建具有值的第三列 (Find ia a strn column is in a list column in the same data frame and create a 3rd column with a value)

在算術表達式中使用字符串是否安全? (Is it safe to use strings in arithmetic expressions?)







留言討論